package com.slaffka.controllers;

import com.slaffka.services.ServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * _User: v.tsapaev
 * Date: 22.02.12
 * Time: 0:22
 * To change this template use File | Settings | File Templates.
 */

//@WebListener
public class HttpSessionStorage implements HttpSessionListener{

    @Autowired
    ServiceFactory service;

    public void setService(ServiceFactory service) {
        System.out.println("*******setServiceFactory");
        this.service = service;
    }

    private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();

    private void initApplicationContext(HttpSessionEvent httpSessionEvent){
        HttpSession session = httpSessionEvent.getSession();
        WebApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(
                        session.getServletContext()
                );
        service = (ServiceFactory)context.getBean("serviceFactory");
    }
    
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        initApplicationContext(httpSessionEvent);

        HttpSession session = httpSessionEvent.getSession();
        sessions.put(session.getId(), session);
        service.getUserSessionService().createUserSession(session.getId(), null);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        sessions.remove(httpSessionEvent.getSession().getId());
        service.getUserSessionService().removeUserSession(httpSessionEvent.getSession().getId());
    }


}
